package com.hougong.im.transport;

import com.hougong.im.pool.ConnPool;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.util.ReferenceCountUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.atomic.AtomicBoolean;

/**
 * 心跳检测Handler
 *
 * @author lsz.
 */
public class HeartbeatHandler extends ChannelInboundHandlerAdapter {
    private static final Logger logger = LoggerFactory.getLogger(HeartbeatHandler.class);

    public static AtomicBoolean isLogout = new AtomicBoolean(false);

    private Long uid;
    // 丢失的心跳数
    private int counter = 0;

    //Idle 读、写、读写超时则触发
    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (evt instanceof IdleStateEvent) {
            // 心跳丢失
            counter++;
            if(uid!=null){
                logger.info(uid + " 丢失" + counter + "个心跳包");
            }else {
                logger.info("无用的channel "+ " 丢失" + counter + "个心跳包");
            }
            if (counter > 4) {
                // 心跳丢失数达到5个，主动断开连接
                ctx.channel().close();
            }
        }
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        if(uid!=null){
            String id = ConnPool.queryTCP(uid).id().asLongText();
            logger.info("当前uid"+uid+"的channle id="+id+"  当前channel的id="+ctx.channel().id().asLongText());
            if(id.equals(ctx.channel().id().asLongText())){
                ConnPool.removeTCP(uid);
                logger.info("用户"+uid+"退出");
            }else {
                logger.info("用户重新登录了，之前的通道关闭");
            }
        }else {
            logger.info("无用的连接关闭");
        }
        super.channelInactive(ctx);
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        if (msg instanceof BaseFrame) {
            BaseFrame baseFrame = (BaseFrame) msg;
            if (baseFrame.getBizType()==0x0002) {
                // 心跳丢失清零
                counter = 0;
                if(uid!=null){
//                    logger.info("收到用户id :"+uid + " 心跳包");
                }else {
                    logger.error("没有登录，怎么来了心跳数据的，app异常？？？");
                }
                ReferenceCountUtil.release(msg);
            } else {
                ctx.fireChannelRead(msg);
            }
        }
    }

    public Long getUid() {
        return uid;
    }

    public void setUid(Long uid) {
        this.uid = uid;
    }
}